const fs = require('fs');
const path = require('path');
const https = require('https');
const axios = require('axios'); // 需要安装：npm install axios

// 配置
const DOMAIN = 'https://file.sheepjs.com/'; // 替换为你的实际域名
const SEARCH_DIRS = ['sheep','pages']; // 搜索目录
const OUTPUT_DIR = path.resolve('D:/static/static'); // 下载到的本地目录
// 支持的图片格式
const IMAGE_EXT_REGEX = /\.(png|jpe?g|gif|webp|bmp|svg|ico|tiff?|avif)$/i;

// 正则：只匹配 /static/ 开头 + 图片扩展名结尾
const REGEX = /(?<=["']?)\/static\/[^"' >)+]+\.(png|jpe?g|gif|webp|bmp|svg|ico|tiff?|avif)(?=["']?)/gi;

// 创建下载目录
if (!fs.existsSync(OUTPUT_DIR)) {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
}

// 收集所有匹配的静态资源路径
const foundPaths = new Set();

// 搜索并过滤
function searchFiles(dir) {
  const items = fs.readdirSync(dir);
  for (const item of items) {
    const fullPath = path.join(dir, item);
    const stat = fs.statSync(fullPath);
    if (stat.isDirectory()) {
      searchFiles(fullPath);
    } else if (stat.isFile() && (item.endsWith('.vue') || item.endsWith('.js') || item.endsWith('.ts'))) {
      const content = fs.readFileSync(fullPath, 'utf-8');
      const matches = content.match(REGEX);
      if (matches) {
        matches.forEach(match => {
          if (IMAGE_EXT_REGEX.test(match)) {
            foundPaths.add(match);
          } else {
            console.log(`🟡 跳过非图片: ${match}`);
          }
        });
      }
    }
  }
}

// 下载单个文件
function downloadFile(url, filepath) {
  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(filepath);
    https.get(url, (response) => {
      if (response.statusCode === 200) {
        response.pipe(file);
        file.on('finish', () => {
          file.close();
          console.log(`✅ 下载成功: ${url} -> ${filepath}`);
          resolve();
        });
      } else {
        console.warn(`❌ 下载失败 (${response.statusCode}): ${url}`);
        fs.unlinkSync(filepath); // 删除空文件
        resolve(); // 继续其他
      }
    }).on('error', (err) => {
      console.error(`⚠️ 下载错误: ${url}`, err.message);
      fs.unlinkSync(filepath);
      resolve();
    });
  });
}

// 主函数
async function main() {
  console.log('🔍 正在扫描项目中的 /static/ 资源...');
  SEARCH_DIRS.forEach(dir => {
    if (fs.existsSync(dir)) {
      searchFiles(dir);
    } else {
      console.warn(`⚠️ 目录不存在: ${dir}`);
    }
  });

  const urls = Array.from(foundPaths).map(p => ({
    url: DOMAIN + p,
    path: path.join(OUTPUT_DIR, p.replace('/static/', ''))
  }));

  console.log(`\n📊 找到 ${urls.length} 个静态资源，开始下载...\n`);

  // 并发下载（可控制并发数）
  const promises = urls.map(({ url, path: localPath }) => {
    const filePath = path.resolve(OUTPUT_DIR, localPath);
    const dir = path.dirname(filePath);
    if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
    return downloadFile(url, filePath);
  });

  await Promise.all(promises);
  console.log('\n🎉 所有资源下载完成！');
  console.log(`📁 文件保存在: ./${OUTPUT_DIR}/`);
}

main().catch(console.error);
